package com.fire8.dolphin.ui.plan;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;

import com.fire8.dolphin.db.PlanDAO;
import com.fire8.dolphin.model.DateModel;
import com.fire8.dolphin.model.Plan;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.PullToRefreshListView;
import com.fire8.dolphin.ui.PullToRefreshListView.OnRefreshListener;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.ui.plan.PlanListAdapter.OnSubItemClickListener;
import com.fire8.dolphin.utils.DateUtil;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;

/**
 * 康复计划主页
 * <功能详细描述>
 *
 * @author  wangchd
 * @version [版本号,2013-1-14]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class PlanListActivity extends Activity
{
    
    //private PullDownView pullDownView;
    private PullToRefreshListView lvPlanList;
    //用于存放多个VIEW
    private PlanListAdapter lvMyAdapter;
    
//    private ScrollOverListView lvPlanList;
    /**我关注的计划**/
    private ListView lvPlanOther;
    /**最新动态**/
    private ListView lvPlanNews;
    /**我自己的**/
    private RadioButton btnButton0;
    /**我所关注的**/
    //private RadioButton btnButton1;
    /**最新动态**/
    private RadioButton btnButton2;
    
    
    private PlanDAO pdDAO;
    private PlanNewsAdapter newsAdapter;
    private DolphinApplication app;
    private List<Plan> planList = new ArrayList<Plan>();
    private List<Plan> planNewsList = new ArrayList<Plan>();
    
    private List<DateModel> dateList = new ArrayList<DateModel>();
    
    final String dayNames[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    
    private PopupWindow popButtonWin;
    //private HashMap<Integer,LinkedHashMap<String, View>> itemViewMap = new HashMap<Integer, LinkedHashMap<String,View>>();
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.plan_list);
        app = (DolphinApplication)getApplication();
        pdDAO = new PlanDAO(PlanListActivity.this);
        Button bt1 = (Button)findViewById(R.id.title_bt_left);
        Button bt2 = (Button)findViewById(R.id.title_bt_right);
        initDateList();//初始化日期列表
        
        lvPlanOther = (ListView)findViewById(R.id.lv_plan_other);
        lvPlanNews = (ListView)findViewById(R.id.lv_news);
        newsAdapter = new PlanNewsAdapter(PlanListActivity.this, planNewsList);
        lvPlanNews.setAdapter(newsAdapter);
        
        btnButton0 = (RadioButton)findViewById(R.id.radio_button0);
        //btnButton1 = (RadioButton)findViewById(R.id.radio_button1);
        btnButton2 = (RadioButton)findViewById(R.id.radio_button2);
        btnButton0.setOnClickListener(new RadioButtonListener());
        //btnButton1.setOnClickListener(new RadioButtonListener());
        btnButton2.setOnClickListener(new RadioButtonListener());
        lvPlanList = (PullToRefreshListView) findViewById(R.id.pulldownview);

        bt2.setOnClickListener(new OnClickListener()
        {
            
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent(PlanListActivity.this,
                        PlanAddActivity2.class);
                startActivity(intent);
            }
        });
        
        
        //取得PLAN的数据
        planList = pdDAO.findList(null);
        //lvMyAdapter = new MyAdapter(PlanListActivity.this);
        lvMyAdapter = new PlanListAdapter(PlanListActivity.this,dateList,planList);
        lvMyAdapter.setOnSubItemClickListener(new OnSubItemClickListener()
        {
            @Override
            public void onClick(View v,int index)
            {
                LogUtil.d("onclick id="+v.getTag());
                createPopupWindow(v,index);
            }
        });
        lvPlanList.setAdapter(lvMyAdapter);
//        pullDownView.notifyDidRefresh(false);
        
        lvPlanList.setOnItemClickListener(new OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id)
            {
                LogUtil.d("onItemClick");
            }
        });
        
        lvPlanList.setOnRefreshListener(new OnRefreshListener()
        {
            
            @Override
            public void onRefresh()
            {
                LogUtil.d("OnRefreshListener");
                //增加前5天日期记录
                
                Date date = new Date();
                if(!dateList.isEmpty())
                {
                    date = dateList.get(0).toDate();
                }
                Calendar c = Calendar.getInstance();
                c.setFirstDayOfWeek(Calendar.SUNDAY);
                c.setTime(date);
                for (int i = 1; i < 6; i++)
                {
                    c.add(Calendar.DATE, -1);
                    DateModel temp = new DateModel(c);
                    dateList.add(0, temp);
                }
                lvMyAdapter.setPlanList(planList);
                lvMyAdapter.notifyDataSetChanged();
                //加载前5天的数据
                lvPlanList.onRefreshComplete();
            }
        });
        
    }
    class RadioButtonListener implements OnClickListener
    {

        @Override
        public void onClick(View v)
        {
            if(v.getId() == btnButton0.getId())
            {
                lvPlanNews.setVisibility(View.GONE);
                lvPlanList.setVisibility(View.VISIBLE);
            }else
            {
                lvPlanList.setVisibility(View.GONE);
                lvPlanNews.setVisibility(View.VISIBLE);
                new GetDataTask().execute(null);
                
            }
        }
        
    }
    /**
     * 初始化日期列表
     * <功能详细描述> [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    private void initDateList()
    {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.SUNDAY);
        for (int i = 2; i > 0; i--)
        {
            c.add(Calendar.DATE, -i);
            DateModel dm = new DateModel();
            dm.setCurrYear(c.get(Calendar.YEAR));
            dm.setCurrMonth(c.get(Calendar.MONTH) + 1);
            dm.setCurrDay(c.get(Calendar.DATE));
            dm.setCurrWeek(c.get(Calendar.DAY_OF_WEEK));
            dateList.add(dm);
            c.add(Calendar.DATE, i);
        }
        c.setTime(new Date());
        for (int i = 0; i < 30; i++)
        {
            if (i != 0)
                c.add(Calendar.DATE, 1);
            DateModel dm = new DateModel();
            dm.setCurrYear(c.get(Calendar.YEAR));
            dm.setCurrMonth(c.get(Calendar.MONTH) + 1);
            dm.setCurrDay(c.get(Calendar.DATE));
            dm.setCurrWeek(c.get(Calendar.DAY_OF_WEEK));
            dateList.add(dm);
        }
    }
    
    /**弹出窗口，显示“删除”、“完成”按钮**/
    private void createPopupWindow(View view,final int index)
    {
        final Long planId = (Long)view.getTag();
        
        if (popButtonWin == null)
        {
            LayoutInflater factory = LayoutInflater.from(this); //加载popWindow的layout   
            final View buttonView = factory.inflate(R.layout.plan_list_long_click,
                    null);
            popButtonWin = new PopupWindow(buttonView, 300, 62); //请注意，使用此构造方法，一定要指定popupWindow的长宽，之后调用popupWindow的showAXXX方法才会显示指定的contentView
            ColorDrawable cd = new ColorDrawable(-0000);
            popButtonWin.setBackgroundDrawable(cd);
            popButtonWin.setFocusable(true);
        }
        popButtonWin.setTouchInterceptor(new OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE)
                {
                    LogUtil.d("按到外面了，关闭窗口");
                    popButtonWin.dismiss();
                    return true;
                }
                return false;
            }
        });
        popButtonWin.getContentView().findViewById(R.id.btn_del_plan).setOnClickListener(new OnClickListener()
        {
            
            @Override
            public void onClick(View v)
            {
                
                Plan plan = pdDAO.getPlan(planId);
                if(plan != null)
                {
                    pdDAO.deletePlan(planId);
                    new UpdatePlanTask().execute(String.valueOf(plan.getsRemoteId()),"0");
                    planList = pdDAO.findList(null);
                    lvMyAdapter.setPlanList(planList);
                    lvMyAdapter.notifyDataSetChanged();
                }
                
                popButtonWin.dismiss();
            }
        });
        popButtonWin.getContentView().findViewById(R.id.btn_finish_plan).setOnClickListener(new OnClickListener()
        {
            
            @Override
            public void onClick(View v)
            {
                
                Plan plan = pdDAO.getPlan(planId);
                if(null!=plan){
                    plan.setFinish(Plan.FINISH_YES);
                    pdDAO.update(plan);
                    LogUtil.d("完成计划");
                    new UpdatePlanTask().execute(String.valueOf(plan.getsRemoteId()),"1");
                    planList = pdDAO.findList(null);
                    lvMyAdapter.setPlanList(planList);
                    lvMyAdapter.notifyDataSetChanged();
                    //弹出窗口提示：立即分享到能量广场分享今天的心情
                }
                
                popButtonWin.dismiss();
            }
        });
        
        popButtonWin.showAsDropDown(view);
    }
        
    @Override
    protected void onRestart()
    {
        super.onRestart();
        LogUtil.d("onRestart");
        planList = pdDAO.findList(null);
        lvMyAdapter.setPlanList(planList);
        lvMyAdapter.notifyDataSetChanged();
    }
    
    @Override
    protected void onResume()
    {
        super.onResume();
        LogUtil.d("onResume");
    }
    /**异步加载“动态”栏数据**/
    private class GetDataTask extends AsyncTask<Integer, Void, String> {

        @Override
        protected String doInBackground(Integer... params) {
            // 在这里可以做一些后台工作
            if(!RequestUtils.getInstall().isConnect(PlanListActivity.this))
            {
                return "网络不可用";
            }
            try
            {
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("startDate",DateUtil.getDayDate()));
                String json = RequestUtils.getInstall().getHttpJson(DolphinApplication.URL+"plan/findOtherPlanList.php", param);
                if(!StringUtil.isEmpty(json))
                {
                    LogUtil.d(json);
                    JSONObject data = new JSONObject(json);
                    String msgCode = data.getString("msgCode");
                    String desc = data.getString("desc");
                    if("1".equals(msgCode))
                    {
                        
                        List<Plan> todays = new ArrayList<Plan>();//今天的计划
                        List<Plan> tomorrows = new ArrayList<Plan>();//明天的计划
                        List<Plan> yesterdays = new ArrayList<Plan>();//昨天的计划
                        List<Plan> agos = new ArrayList<Plan>();//更早之前的
                        String today = DateUtil.getDayDate();
                        String tomorrow = DateUtil.getDifferenceNowDate(Calendar.DATE, 1, "yyyy-MM-dd");
                        String yesterday = DateUtil.getDifferenceNowDate(Calendar.DATE, -1, "yyyy-MM-dd");
                        JSONArray jsonArray = data.getJSONArray("msgBody");
                        int len = jsonArray.length();
                        for (int i = 0; i < len; i++)
                        {
                            
                            JSONObject object = jsonArray.getJSONObject(i);
                            String date = object.getString("alarmTime");
                            //LogUtil.d("alarmTime="+date);
                            Plan mPlan = new Plan();
                            mPlan.setTitle(object.getString("title"));
                            mPlan.setUserId(object.getInt("userId"));
                            mPlan.setUserName(object.getString("userName"));
                            //mPlan.setDateTime(object.getString("dateTime"));
                            mPlan.setAlarmTime(date);
                            mPlan.setDataType(Plan.DATA_TYPE_PLAN);
                            if(date.contains(today))
                            {
                                todays.add(mPlan);
                            }else if(date.contains(tomorrow))
                            {
                                tomorrows.add(mPlan);
                            }else if(date.contains(yesterday))
                            {
                                yesterdays.add(mPlan);
                            }else
                            {
                                agos.add(mPlan);
                            }
                            
                        }
                        planNewsList.clear();
                        if(!todays.isEmpty())
                        {
                            Plan dayPlan = new Plan();
                            dayPlan.setTitle("今天");
                            dayPlan.setDataType(Plan.DATA_TYPE_TITLE);
                            planNewsList.add(dayPlan);
                            planNewsList.addAll(todays);
                        }
                        if(!tomorrows.isEmpty())
                        {
                            Plan dayPlan = new Plan();
                            dayPlan.setTitle("明天");
                            dayPlan.setDataType(Plan.DATA_TYPE_TITLE);
                            planNewsList.add(dayPlan);
                            planNewsList.addAll(tomorrows);
                        }
                        if(!yesterdays.isEmpty())
                        {
                            Plan dayPlan = new Plan();
                            dayPlan.setTitle("昨天");
                            dayPlan.setDataType(Plan.DATA_TYPE_TITLE);
                            planNewsList.add(dayPlan);
                            planNewsList.addAll(yesterdays);
                        }
                        if(!agos.isEmpty())
                        {
                            Plan dayPlan = new Plan();
                            dayPlan.setTitle("更早");
                            dayPlan.setDataType(Plan.DATA_TYPE_TITLE);
                            planNewsList.add(dayPlan);
                            planNewsList.addAll(agos);
                        }
                    }else
                    {
                        LogUtil.e(desc);
                    }
                }
            }
            catch (Exception e)
            {
                LogUtil.e("",e);
            }
            
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            newsAdapter.setPlanList(planNewsList);
            newsAdapter.notifyDataSetChanged();
        }
    }
    /**更新服务器端计划状态
     * 参数一：计划ID
     * 参数二：指令代码[0：删除；1：完成]
    **/
    private class UpdatePlanTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... arg0)
        {
            if(!RequestUtils.getInstall().isConnect(PlanListActivity.this))
            {
                return "网络不可用";
            }
            try
            {
                LogUtil.d("planId="+arg0[0]);
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("myPlan.planId",arg0[0]));
                param.add(new BasicNameValuePair("command",arg0[1]));
                param.add(new BasicNameValuePair("myPlan.userId",app.getUserId()));
                RequestUtils.getInstall().getHttpJson(DolphinApplication.URL+"plan/updatePlan.php", param);
                LogUtil.d("更新计划状态");
            }
            catch (Exception e)
            {
                LogUtil.e("",e);
            }
            return null;
        }
    }
}